//
//  HYFUserAccountViewModel.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/7/22.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

import UIKit

class HYFUserAccountViewModel: NSObject {
    
    //路径
    let file = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
    
    //全局访问点
    static let sharedTools:HYFUserAccountViewModel = HYFUserAccountViewModel()
    
    //创建一个用户模型
    var userAccount:HYFUserAccount?
    
    //判断 accessToken 是否过期
    var accessToken:String?{
        
        if userAccount?.access_token != nil {
            
            //看看是否过期   OrderedDescending --> 降序 --> 未过期
            if userAccount?.exprires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                
                return userAccount?.access_token
            }else {
            //表示已经过期
                return nil
            }
            
        }else{
            //代表没有 accessToken
                return nil
        }
    }
    
    //判断用户是否登录
    var isLogin:Bool{
        
        return accessToken != nil
    }
    
    
    override init() {
        super.init()
        
       //赋值 userAccount
        userAccount = getUserAccount()
    }
}


//MARK:归档和解档
extension HYFUserAccountViewModel {
    
    //保存对象
    func saveUserAccount(userAccount:HYFUserAccount){
        
        //为了解决第一次的 userAccount 为 nil 的 bug
        self.userAccount = userAccount
        
        //保存对象
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: file)
    }
    
    //获取对象
    func getUserAccount()-> HYFUserAccount?{
        
        //获取对象
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? HYFUserAccount
        
        return result
        
    }
}


extension HYFUserAccountViewModel{
    
    func loadUserAccount(code:String,isSuccess:(isSuc:Bool)->()){
        
        HYFNetworkTools.shardTools.oauthLoadUserAccount(code, success: { (response) in
            
            guard let res = response as? [String:AnyObject] else{
                
                isSuccess(isSuc: false)
                return
            }
            
            //字典转模型
            let userAccount = HYFUserAccount(dict: res)
            self.loadUserInfo(userAccount, isSuccess: isSuccess)
            
        }) { (error) in
            print("请求失败\(error)")
            isSuccess(isSuc: false)
        }
    }
    
    
    func loadUserInfo(userAccount:HYFUserAccount,isSuccess:(isSuc:Bool)->()){
        
        HYFNetworkTools.shardTools.oauthLoadUserInfo(userAccount, success: { (response) in
            
            // 判断response是否为nil 而且是否可以转成字典
            guard let res = response as? [String: AnyObject] else{
                
                isSuccess(isSuc: false)
                return
            }
            // 因为当前的screenname 和avatar_large 本来就是可选值 所以在as的时候 只用as? 转字符串
            // 给其userAccount身上两个为nil的属性赋值
            userAccount.sreen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
           
            //通过归档保存数据
            self.saveUserAccount(userAccount)
            
            isSuccess(isSuc: true)
            
        }) { (error) in
            
            print("请求失败:\(error)")
            isSuccess(isSuc: false)
        }
    }
}